<?php

class Application_Model_Users extends Application_Model_Base{
    private static $instance = null;
    public static function getInstance(){
        if (null === self::$instance) self::$instance = new self();
        return self::$instance;
    }
    private function __clone() {}
    private function __construct() {}

    public function getPaginatorForFilter($params){
        //var_dump($params);
        $select = $this->getDBAdapter()->select()
            ->from('users');
        if (!empty($params['user_name'])){
            $select->where("`user_name` LIKE '%{$params['user_name']}%'");
        }
        if (!empty($params['user_surname'])){
            $select->where("`user_surname` LIKE '%{$params['user_surname']}%'");
        }
        if (!empty($params['user_patronymic'])){
            $select->where("`user_patronymic` LIKE '%{$params['user_patronymic']}%'");
        }
        if (!empty($params['user_birth_date'])){
            $select->where("`user_birth_date` LIKE '%{$params['user_birth_date']}%'");
        }
        $paginatorAdapter = new Zend_Paginator_Adapter_DbSelect($select);
        return new Zend_Paginator($paginatorAdapter);
    }

    public function getAll(){
        return $this->getDBAdapter()->query("
            select * from `users`
        ")->fetchAll();
    }

    public function createForRegister($data){
        $userTypeId = $this->getDBAdapter()->query("
            select * from `user_types`
            where `user_type_key` = 'user'
        ")->fetchAll();
        $userTypeId = $userTypeId[0];
        $userTypeId = $userTypeId['user_type_id'];
        $data['fk_user_types_id'] = $userTypeId;
        $this->create($data);
    }

    public function getAllForSelect(){
        $users = $this->getDBAdapter()->query("
            select `user_id`, `user_name` from `users`
        ")->fetchAll();
        $usersForSelect = array();
        foreach($users as $user){
            $usersForSelect[$user['user_id']] = $user['user_name'];
        }
        return $usersForSelect;
    }

    public function create($data){
        $this->getDBAdapter()->insert('users', $data);
    }

    public function login($data){
        $login = $data['user_login'];
        $password = $data['user_password'];
        $currentUser = $this->getDBAdapter()->query("
            select * from `users`
            left join `user_types`
            on(`users`.`fk_user_types_id` = `user_types`.`user_type_id`)
            where `users`.`user_login` = '{$login}'
            and `users`.`user_password` = '{$password}'
        ")->fetchAll();
        if(count($currentUser) == 1){
            return $currentUser['0'];
        }
        return false;
    }
}

